package hsfslow2fast;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.function.Consumer;

/**
 * @author chaird
 * @create 2022-10-22 15:29
 */
@Component
public class FastBeanFactoryProcessor implements BeanFactoryPostProcessor {
  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
      throws BeansException {

    String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();

    Class<? extends Class> aClass = Consumer.class.getClass();

    Map<String, Hsfconsumer> consumerMap = new HashMap<>();
    for (String beanDefinitionName : beanDefinitionNames) {

      if (beanDefinitionName.contains("consumer")) {

        Hsfconsumer hsfconsumer = new Hsfconsumer();
        consumerMap.put(beanDefinitionName, hsfconsumer);
      }


    }

    CountDownLatch countDownLatch = new CountDownLatch(consumerMap.size());

    for (Map.Entry<String, Hsfconsumer> stringConsumerEntry : consumerMap.entrySet()) {

      new Thread(
              new Runnable() {
                @Override
                public void run() {
                  stringConsumerEntry.getValue().init();
                  countDownLatch.countDown();
                }
              },
              "name")
          .start();
    }

    try {
      countDownLatch.await();
    } catch (Exception e) {
      e.printStackTrace();
    }

    for (Map.Entry<String, Hsfconsumer> stringConsumerEntry : consumerMap.entrySet()) {
      beanFactory.registerSingleton(stringConsumerEntry.getKey(), stringConsumerEntry.getValue());
    }



  }
}
